Page({
  data: {
    historyList: []
  },

  onShow() {
    this.loadHistory()
  },

  loadHistory() {
    const history = wx.getStorageSync('calculation_history') || []
    const historyList = history.map(item => ({
      ...item,
      formattedTime: this.formatTime(new Date(item.timestamp))
    }))
    this.setData({ historyList })
  },

  formatTime(date) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    return `${year}/${month}/${day} ${hour}:${minute}`
  },

  clearHistory() {
    wx.showModal({
      title: '确认清空',
      content: '是否清空所有历史记录？',
      success: (res) => {
        if (res.confirm) {
          wx.setStorageSync('calculation_history', [])
          this.setData({ historyList: [] })
          wx.showToast({
            title: '已清空',
            icon: 'success'
          })
        }
      }
    })
  },

  deleteRecord(e) {
    const { index } = e.currentTarget.dataset
    const history = wx.getStorageSync('calculation_history')
    history.splice(index, 1)
    wx.setStorageSync('calculation_history', history)
    this.loadHistory()
  },

  useRecord(e) {
    const { index } = e.currentTarget.dataset
    const record = this.data.historyList[index]
    wx.navigateTo({
      url: '/pages/calculator/calculator',
      success: (res) => {
        res.eventChannel.emit('useHistoryRecord', record)
      }
    })
  },

  exportHistory() {
    // 导出功能可以根据实际需求实现
    // 例如：生成Excel文件或分享文本
    wx.showToast({
      title: '导出功能开发中',
      icon: 'none'
    })
  }
})
